<template>
  <div class="article-container">
    <!-- 导航栏 -->
    <van-nav-bar
      class="page-nav-bar"
      left-arrow
      title="黑马头条"
      @click-left="onClickLeft"
    ></van-nav-bar>
    <!-- /导航栏 -->

    <div class="main-wrap">
      <!-- 加载中 -->
      <div class="loading-wrap" v-if="loading">
        <van-loading color="#3296fa" vertical>加载中</van-loading>
      </div>
      <!-- /加载中 -->

      <!-- 加载完成-文章详情 -->
      <div class="article-detail" v-else-if="status === 200">
        <!-- 文章标题 -->
        <h1 class="article-title">{{ thearticle.title }}</h1>
        <!-- /文章标题 -->

        <!-- 用户信息 -->
        <van-cell class="user-info" center :border="false">
          <van-image
            class="avatar"
            slot="icon"
            round
            fit="cover"
            :src="thearticle.aut_photo"
            @click="toAutInfo"
          />
          <div slot="title" class="user-name">{{ thearticle.aut_name }}</div>
          <div slot="label" class="publish-date">{{ thearticle.pubdate | relativeTime }}</div>
          <!-- <van-button
            class="follow-btn"
            type="info"
            color="#3296fa"
            round
            size="small"
            icon="plus"
            v-if="!is_followed"
            @click="onFollowed"
            :loading="btnLoading"
            >关注</van-button
          >
          <van-button
            class="follow-btn"
            round
            size="small"
            @click="quitFollowed"
            :loading="btnLoading"
            v-else
            >已关注</van-button
          > -->
          <btn-following
            :is_followed="is_followed"
            :aut_id="thearticle.aut_id"
            @toFollowed="is_followed = true"
            @quitFollowed="is_followed = false"
          ></btn-following>
        </van-cell>
        <!-- /用户信息 -->

        <!-- 文章内容 -->
        <div class="markdown-body">
          <div class="article-content" v-html="thearticle.content" ref="articleContent"></div>
        </div>

        <van-divider>正文结束</van-divider>

        <!-- 文章评论区域 -->
        <article-comment
          :art_id="thearticle.art_id || 0"
          @sendBadge="badge = $event"
        ></article-comment>
        <!-- /文章评论区域 -->
      </div>
      <!-- /加载完成-文章详情 -->

      <!-- 加载失败：404 -->
      <div class="error-wrap" v-else-if="status === 404">
        <van-icon name="failure" />
        <p class="text">该资源不存在或已删除！</p>
      </div>
      <!-- /加载失败：404 -->

      <!-- 加载失败：其它未知错误（例如网络原因或服务端异常） -->
      <div class="error-wrap" v-else>
        <van-icon name="failure" />
        <p class="text">内容加载失败！</p>
        <van-button class="retry-btn" @click="getNews()">点击重试</van-button>
      </div>
      <!-- /加载失败：其它未知错误（例如网络原因或服务端异常） -->
    </div>

    <!-- 底部区域 -->
    <div class="article-bottom">
      <van-button class="comment-btn" type="default" round size="small" @click="showComment = true"
        >写评论</van-button
      >
      <van-icon name="comment-o" :badge="badge" color="#777" />
      <!-- 收藏组件替代 -->
      <btn-Star
        class="btn-star"
        :is_collected="is_collected"
        :aut_id="thearticle.art_id || 0"
        @toCollect="is_collected = true"
        @quitCollect="is_collected = false"
      ></btn-Star>
      <!-- 点赞组件替代 -->
      <btn-liking
        class="btn-liking"
        :is_liked="is_liked"
        :art_id="thearticle.art_id || 0"
        @toLiking="is_liked = 1"
        @quitLiking="is_liked = -1"
        @toDisLiking="is_liked = 0"
      ></btn-liking>
      <van-icon name="share" color="#777777"></van-icon>
    </div>
    <!-- /底部区域 -->

    <!-- 写评论弹出层 -->
    <van-popup v-model="showComment" position="bottom">
      <comment-pop
        :target="thearticle.art_id"
        @okSend="
          showComment = false
          badge++
        "
      ></comment-pop>
    </van-popup>

    <!-- 回复评论的弹出层 -->
    <van-popup v-model="showReplyComment" position="bottom" style="height: 95%">
      <comment-reply
        :comment="comment"
        :art_id="thearticle.art_id || {}"
        @click-close="showReplyComment = false"
      ></comment-reply>
    </van-popup>
  </div>
</template>

<script>
// 导入获取文章详情的api
import { getNewDetail } from '@/assets/api/article.js'
import { ImagePreview } from 'vant'

// 导入vuex的user
import { mapState } from 'vuex'
// 导入关注组件
import Following from '@/components/btn-following.vue'
// 导入收藏组件
import Star from '@/components/Star.vue'
// 导入点赞组件
import btnLikings from '@/components/btn-likings'
// 导入文章评论模块
import ArticleComment from '@/components/article-comment'
// 导入写评论模块
import commentPop from './components/commentPopup.vue'
// 导入通信组件
import eventHub from '@/assets/utils/communication'
// 导入点击回复的组件
import CommentReply from './components/clickReplyPop.vue'

export default {
  name: 'ArticleIndex',
  props: {
    id: {
      type: [Number, String, Object],
      required: true
    }
  },
  data() {
    return {
      thearticle: {},
      // 控制加载的开启和关闭
      loading: true,
      // 加载的状态
      status: 200,
      // 是否关注
      is_followed: false,
      // 是否收藏
      is_collected: false,
      // 是否喜欢
      is_liked: 0,
      // 评论数量
      badge: 0,
      // 控制写评论的弹出层
      showComment: false,
      // 回复评论的弹出层
      showReplyComment: false,
      // 回复的评论消息
      comment: {}
    }
  },
  methods: {
    // 获取文章详情
    async getNews() {
      this.loading = true
      try {
        var { data: res } = await getNewDetail(this.id)
      } catch (err) {
        this.loading = false
        if (err.response && err.response.status === 404) {
          return (this.status = err.response.status)
        } else {
          return (this.status = 400)
        }
      }
      this.status = 200
      // 数据驱动视图不是理解的
      this.thearticle = res.data
      this.is_followed = res.data.is_followed
      this.is_collected = res.data.is_collected
      if (this.user) {
        this.is_liked = res.data.attitude
      } else {
        this.is_liked = -1
      }
      // 初始化图片预览
      setTimeout(() => {
        this.previewImage(this.$refs.articleContent)
      }, 0)

      this.loading = false
    },
    // 顶部导航栏←按钮
    onClickLeft() {
      this.$router.back()
    },
    // 处理图片预览
    previewImage(dom) {
      // 得到所有img节点
      const imgs = dom.querySelectorAll('img')
      const imgurls = []
      imgs.forEach((item, index) => {
        // 获取所有的url地址
        imgurls.push(item.src)
        // 点击预览
        item.addEventListener('click', () => {
          ImagePreview({
            // 预览的图片数组
            images: imgurls,
            // 从零开始运算
            startPosition: index
          })
        })
      })
    },
    // 跳转到作者详情页
    toAutInfo() {
      this.$router.push({
        path: '/autInfo/' + this.thearticle.aut_id
      })
    }
  },
  created() {
    this.getNews()
    eventHub.$on('showPop', (val) => {
      this.showReplyComment = true
      this.comment = val
      console.log(val)
    })
  },
  computed: {
    ...mapState(['user'])
  },
  components: {
    'btn-following': Following,
    'btn-Star': Star,
    'btn-liking': btnLikings,
    'article-comment': ArticleComment,
    'comment-pop': commentPop,
    'comment-reply': CommentReply
  }
}
</script>

<style scoped lang="less">
@import './markDown.css';
.article-container {
  .main-wrap {
    position: fixed;
    left: 0;
    right: 0;
    top: 92px;
    bottom: 88px;
    overflow-y: scroll;
    background-color: #fff;
  }
  .article-detail {
    .article-title {
      font-size: 40px;
      padding: 50px 32px;
      margin: 0;
      color: #3a3a3a;
    }

    .user-info {
      padding: 0 32px;
      .avatar {
        width: 70px;
        height: 70px;
        margin-right: 17px;
      }
      .van-cell__label {
        margin-top: 0;
      }
      .user-name {
        font-size: 24px;
        color: #3a3a3a;
      }
      .publish-date {
        font-size: 23px;
        color: #b7b7b7;
      }
    }

    .article-content {
      padding: 55px 32px;
      /deep/ p {
        word-break: break-all;
        word-wrap: break-word;
        text-align: justify;
      }
    }
  }

  .loading-wrap {
    padding: 200px 32px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #fff;
  }

  .error-wrap {
    padding: 200px 32px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    background-color: #fff;
    .van-icon {
      font-size: 122px;
      color: #b4b4b4;
    }
    .text {
      font-size: 30px;
      color: #666666;
      margin: 33px 0 46px;
    }
    .retry-btn {
      width: 280px;
      height: 70px;
      line-height: 70px;
      border: 1px solid #c3c3c3;
      font-size: 30px;
      color: #666666;
    }
  }

  .article-bottom {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    justify-content: space-around;
    align-items: center;
    box-sizing: border-box;
    height: 88px;
    border-top: 1px solid #d8d8d8;
    background-color: #fff;
    .comment-btn {
      width: 282px;
      height: 46px;
      border: 2px solid #eeeeee;
      font-size: 30px;
      line-height: 46px;
      color: #a7a7a7;
    }
    .van-icon {
      font-size: 40px;
      .van-info {
        font-size: 16px;
        background-color: #e22829;
      }
    }
    .btn-star,
    .btn-liking,
    /deep/ .btn-liking > .van-button {
      border: 0;
      padding: 0 5px;
    }
  }
}
</style>
